<template>
  <img
    :src="imageSrc"
    :alt="alt"
    :class="imageClass"
    :style="imageStyle"
    @load="onLoad"
    @error="onError"
    v-bind="$attrs"
  />
</template>

<script setup>
import { ref, computed, onMounted, watch, onUnmounted } from 'vue'
import api from '@/services/api'

const props = defineProps({
  src: {
    type: String,
    required: true
  },
  alt: {
    type: String,
    default: ''
  },
  imageClass: {
    type: String,
    default: ''
  },
  imageStyle: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['load', 'error'])

const imageSrc = ref('')
const isLoading = ref(true)
const hasError = ref(false)

// 清理object URL
const cleanup = () => {
  if (imageSrc.value && imageSrc.value.startsWith('blob:')) {
    URL.revokeObjectURL(imageSrc.value)
    imageSrc.value = ''
  }
}

// 获取带认证的图片URL
const fetchAuthenticatedImage = async () => {
  // 清理之前的URL
  cleanup()

  // 重置状态
  isLoading.value = true
  hasError.value = false

  try {
    const token = localStorage.getItem('auth_token')
    if (!token) {
      throw new Error('No authentication token')
    }

    // 使用fetch获取图片，带上认证头
    const response = await fetch(props.src, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Accept': 'image/*'
      },
      credentials: 'include'
    })

    if (!response.ok) {
      const errorText = await response.text()
      throw new Error(`HTTP ${response.status}: ${errorText}`)
    }

    // 检查响应类型
    const contentType = response.headers.get('content-type')
    if (!contentType || !contentType.startsWith('image/')) {
      throw new Error(`Invalid content type: ${contentType}`)
    }

    // 将响应转换为blob，然后创建object URL
    const blob = await response.blob()
    imageSrc.value = URL.createObjectURL(blob)
    isLoading.value = false
  } catch (error) {
    console.error('Failed to load authenticated image:', props.src, error)
    hasError.value = true
    isLoading.value = false
    emit('error', error)
  }
}

const onLoad = (event) => {
  emit('load', event)
}

const onError = (event) => {
  hasError.value = true
  emit('error', event)
}

// 监听src属性变化，重新获取图片
watch(() => props.src, (newSrc) => {
  if (newSrc) {
    fetchAuthenticatedImage()
  }
}, { immediate: true })

// 组件卸载时清理
onUnmounted(cleanup)
</script>

<style scoped>
/* 可以添加加载状态的样式 */
</style>
